<?php

namespace app\common\model;
use think\Model;

class Url extends Model {

    /**
     * 定义主键
     * @var string
     */
    protected $pk = 'id';
    
    /**
     * @desc 生产随机短链
     * @param int $num
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUrlKeyword($num = 6) {
        //随机生产字符串
        $keyword = random_string($num);
        //判断字符是否存在
        $result = $this->isExistsKeyword($keyword);
        if($result){
            $this->getUrlKeyword($num);
        }else{
            return $keyword;
        }
    }
    
    /**
     * @desc 判断url短链是否存在
     * @param $keyword
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isExistsKeyword($keyword) {
        $result = $this->where('keyword', '=', $keyword)->find();
        if($result) {
            return true;
        }
        return false;
    }
}